#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<iostream>
#include<string>
#include<cstring>

void Usage(std::string proc)
{
    std::cout << proc << " port" << std::endl;
}
int main(int args,char* argv[])
{
    if(args != 2)
    {
        Usage(argv[0]);
    }
    //static int port = 8081;
    static int port = atoi(argv[1]);
    //一.创建套接字
    int sock_fd = socket(AF_INET,SOCK_DGRAM,0);

    struct sockaddr_in local;
    //需要主机序列转网络序列 htons/htonl 
    //(ntohs/ntohl)这是网络转主机
    local.sin_port = htons(port);
    local.sin_family = AF_INET;
    //服务器不要指明ip
    //IP需要2点转化
    //1.点分十进制要转化4字节整数IP 
    //2.要转化为大端
    //local.sin_addr.s_addr = inet_addr("127.0.0.1");
    local.sin_addr.s_addr = INADDR_ANY;
    //二.bind
    
    if(bind(sock_fd,(sockaddr*)&local,sizeof(local))<0)
    {
        std::cerr << "bind is error" << errno << std::endl; 
        exit(1);
    }

    //三.提供服务
    #define NUM 1024
    char buffer[NUM];
    memset(buffer,0,sizeof(buffer));
    bool quit = false;
    while(!quit)
    {
        struct sockaddr_in client;
        socklen_t len = sizeof(client);
        //接收信息
        recvfrom(sock_fd,buffer,sizeof(buffer)-1,0,(sockaddr*)&client,&len);
        buffer[sizeof(buffer)-1] = '/0';
        
        std::cout << "client #" << buffer << std::endl;

        //回应客户端
        std::string echo_hello  = "hello";
        sendto(sock_fd,echo_hello.c_str(),echo_hello.size(),0,(sockaddr*)&client,len);

    }

    return 0;
}